package com.tianwen.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianwen.management.entity.Permission;
import com.tianwen.management.entity.Role;
import com.tianwen.management.entity.UserRolePermission;
import com.tianwen.management.service.PermissionService;
import com.tianwen.management.mapper.PermissionMapper;
import com.tianwen.management.service.UserRolePermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author Administrator
* @description 针对表【permission】的数据库操作Service实现
* @createDate 2023-05-12 15:34:17
*/
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
    implements PermissionService{
@Resource
private PermissionMapper permissionMapper;
@Resource
private UserRolePermissionService userRolePermissionService;
    @Override
    public List<Permission> page(Integer page, Integer pageSize, String name) {
        QueryWrapper<Permission> queryWrap=new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(name)){
            queryWrap.like("name",name);
        }
        queryWrap.orderByDesc("id" );
        Page<Permission> pageInfo=new Page<>(page,pageSize);
        List<Permission> permissionList = permissionMapper.selectPage(pageInfo,queryWrap).getRecords();
        return permissionList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeAndRoleAndUser(Long id) {
        permissionMapper.deleteById(id);
        QueryWrapper<UserRolePermission> queryWrap=new QueryWrapper<>();
        queryWrap.eq("permission_id",id);
        userRolePermissionService.remove(queryWrap);
        return true;
    }

    @Override
    public List<Permission> findByRoleId(Long roleId) {
                   QueryWrapper<UserRolePermission> queryWrap=new QueryWrapper<>();
                   queryWrap.eq("is_user",0);
                   queryWrap.eq("role_id",roleId);
        List<UserRolePermission> userRolePermissions = userRolePermissionService.list(queryWrap);
        List<Long> ids=new ArrayList<>();
        userRolePermissions.stream().forEach(userRolePermission->{
            ids.add(userRolePermission.getPermissionId());
        });
        List<Permission> permissionList = permissionMapper.selectBatchIds(ids);
        return permissionList;
    }

}




